package com.gy.hsim.bservice.ecomInfo.restful;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gy.hsim.bservice.ecomInfo.bean.SaleAndOperatorRelation;
import com.gy.hsim.bservice.ecomInfo.bean.UserGroup;
import com.gy.hsim.bservice.ecomInfo.service.EcomInfoService;
import com.gy.hsim.bservice.framework.bean.QueryVerifyReponse;
import com.gy.hsim.bservice.framework.enums.MessageResultEnum;
import com.gy.hsim.bservice.framework.mapper.MessageMapper;
import com.gy.hsim.bservice.framework.restful.BaseController;
import com.gy.hsim.bservice.friendInfo.bean.QueryFriendReq;
import com.gy.hsim.bservice.message.bean.Message;
import com.gy.hsim.bservice.message.bean.MessageSetting;
import com.gy.hsim.bservice.message.service.MessageService;
import com.gy.hsxt.uc.search.api.IUCUserInfoSearchService;
import com.gy.hsxt.uc.search.bean.SearchResult;
import com.gy.hsxt.uc.search.bean.SearchUserInfo;
import com.gy.hsxt.uc.search.bean.SearchUserRole;

/**
 * 
 * @ClassName: EcomInfoController 
 * @Description: 查询 电商相关信息Controller 
 * @author quanrj 
 * @date 2016-03-01 上午09:37:19
 */
@Controller
@RequestMapping("/ecomInfo")
public class EcomInfoController extends BaseController {
	private static final Logger log = LoggerFactory
			.getLogger(Message.class);
	
	@Autowired
	private EcomInfoService ecomInfoService;
	
	@Autowired
	private IUCUserInfoSearchService userInfoSearchService;
	
	/**餐饮订单业务代码常量，用户过滤根据业务类型过滤不符合角色的操作员*/	
	public static final String MSG_CODE_02541 = "02541";            //店内订单定金支付成功,推送给(店铺管理员,收银员,服务员)
	public static final String MSG_CODE_02542 = "02542";            //支付成功(店内-支付尾款),推送给(店铺管理员,收银员)
	public static final String MSG_CODE_02543 = "02543";            //外卖消费者申请取消,推送给(店铺管理员,收银员)
	public static final String MSG_CODE_02544 = "02544";            //送餐提醒(外卖-送餐),推送给(送餐员)
	public static final String MSG_CODE_02545 = "02545";            //取消订单(店内-消费者申请取消),推送给(店铺管理员,收银员)
	public static final String MSG_CODE_02546 = "02546";            //消费者自提下单(店内－自提下单),推送给(店铺管理员,收银员,服务员)
	public static final String MSG_CODE_02547 = "02547";            //消费者外卖下单(外卖－下单),推送给(店铺管理员,收银员,服务员)
	
	/**企业操作员角色常量，用于在餐饮订单中过滤不符合角色的操作员**/	
	public static final String ROLE_202 = "202";                    //成员企业店铺管理员
	public static final String ROLE_302 = "302";                    //托管企业店铺管理员
	public static final String ROLE_303 = "303";                    //托管企业收银员
	public static final String ROLE_203 = "203";                    //成员企业收银员
	public static final String ROLE_204 = "204";                    //成员企业服务员
	public static final String ROLE_304 = "304";                    //托管企业服务员
	public static final String ROLE_6301 = "6301";                  //DCIS系统管理员
	public static final String ROLE_205 = "205";                    //成员企业送餐员
	public static final String ROLE_305 = "305";                    //托管企业送餐员
		
	/**
	 * 查询营业点下操作员接口URL: http://localhost:9090/hsim-bservice/ecomInfo/queryAllOperatorBySaleNetwork
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/queryAllOperatorBySaleNetwork",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse queryAllOperatorBySaleNetwork(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		QueryVerifyReponse resp = new QueryVerifyReponse();
		List<SaleAndOperatorRelation> SaleAndOperatorRelationList = new ArrayList<SaleAndOperatorRelation>();
		//获取前端传过来的查询参数			
		JSONObject object = (JSONObject)request.getAttribute("object");
		SaleAndOperatorRelation saleAndOperatorRelation = JSON.toJavaObject(object, SaleAndOperatorRelation.class);
		System.out.println("【接收到的json】：" + object);
		log.debug("【接收到的json】：" + object);
		
		String msgCode = saleAndOperatorRelation.getMsgCode();
		String enterprise = "";
		try {
			//由IM系统传过来的enterprise会把资源号的最前面的0都截取掉，这边先把0补齐
			String manOperCustid = saleAndOperatorRelation.getEnterprise();
			if(manOperCustid != null && !manOperCustid.equals("")){
				int enterpriseLen = manOperCustid.length();
				for (int i = enterpriseLen; i < 19; i++) {       //UC3.0的客户号是19位
					manOperCustid = "0" + manOperCustid;
				}
				enterprise = manOperCustid.substring(0,11);     //由IM系统传过来的enterprise是该企业下系统操作员（0000用户）的客户号，这里截取11位数得到该企业的资源号
			}
						
			SaleAndOperatorRelationList = ecomInfoService.queryAllOperatorBySale_network(enterprise, saleAndOperatorRelation.getSale_network());
			List<String> realOperatorCustIdList = new ArrayList<String>();
			
			/**找出符合业务需求的操作员*/
			if(SaleAndOperatorRelationList !=null && SaleAndOperatorRelationList.size() > 0){		
				
				/*1.用户中心查询该企业下的所有操作员列表*/
				SearchResult<SearchUserInfo> result = userInfoSearchService.getOpersByEntCustId(enterprise);
				List<SearchUserInfo> searchUserInfoDataList =  result.getList();
				List<SearchUserInfo> searchUserInfoList =  new ArrayList<SearchUserInfo>();
				
				/*2.找出属于这个营业点下的所有操作员*/				
				for(SaleAndOperatorRelation saleAndOperatorRelationData : SaleAndOperatorRelationList){
					for(SearchUserInfo searchUserInfoData :searchUserInfoDataList){
						String operatorSign = enterprise + saleAndOperatorRelationData.getOperator();
						if(searchUserInfoData.getCustId().indexOf(operatorSign) >= 0){
							searchUserInfoList.add(searchUserInfoData);
							break;
						}
					}
				}
				
				/*3.找出这个营业点下符合角色的所有操作员*/
				if(searchUserInfoList != null && searchUserInfoList.size() > 0){
					List<SearchUserRole> userRoleList = new ArrayList<SearchUserRole> ();
					for(SearchUserInfo searchUserInfo : searchUserInfoList){
						//用list存储某操作员的所有角色Id
						List<String> userRoleIdList = new ArrayList<String>();
						userRoleList = searchUserInfo.getUserRole();
						if(userRoleList !=null && userRoleList.size() > 0){
							for(int i=0;i<userRoleList.size();i++){
								String userRoleId = String.valueOf(userRoleList.get(i).getRoleId());
								userRoleIdList.add(userRoleId);
							}
						}
						//根据餐饮业务的不同业务场景以及该操作员所有角色去判断是否把消息推送给该操作员，如果是则把这个操作员的custId存到list中
						if (ifOperatorHasRole(msgCode, userRoleIdList)) {
							realOperatorCustIdList.add(searchUserInfo.getCustId().toString());
						}
					}
				}
												
			}
			/**如果找不到合适的操作员，则返回企业管理员（0000操作员）*/
			if(realOperatorCustIdList == null || realOperatorCustIdList.size() == 0){
				if(manOperCustid != null && !manOperCustid.equals("")){
					realOperatorCustIdList.add(manOperCustid);
				}				
			}
			int totalRows = realOperatorCustIdList.size();						
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			resp.setRows(realOperatorCustIdList);
			resp.setTotalRows(totalRows);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
			resp.setTotalRows(0);
		}
       return resp;
	}
	
	/**
	 * 查询消费者关注商品接口URL: http://localhost:9090/hsim-bservice/ecomInfo/getDesUids
	 * 
	 * @param request
	 * @param response
	 * @return 响应返回实体类，含返回码、响应消息
	 * @throws Exception 
	 */
	@RequestMapping(value = "/getDesUids",method = RequestMethod.POST)
	public  @ResponseBody QueryVerifyReponse getDesUids(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		QueryVerifyReponse resp = new QueryVerifyReponse();
		List<UserGroup> userGroupList = new ArrayList<UserGroup>();
		//获取前端传过来的查询参数			
		JSONObject object = (JSONObject)request.getAttribute("object");
		UserGroup userGroup = JSON.toJavaObject(object, UserGroup.class);
		System.out.println("【接收到的json】：" + object);
		log.debug("【接收到的json】：" + object);
		try {
			userGroupList = ecomInfoService.getDesUids(userGroup.getGroupId());
			//返回数据到im中不需要用户类型,只需要客户号就可以了
			for(UserGroup userGroupData : userGroupList){
				String userId = userGroupData.getUser_id();
				userId = userId.substring(userId.lastIndexOf("_")+1);
				userGroupData.setUser_id(userId);
			}
			int totalRows = userGroupList.size();
			resp.setRetCode(MessageResultEnum.EXEC_SUCCESS.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_SUCCESS.getMessage());
			resp.setRows(userGroupList);
			resp.setTotalRows(totalRows);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e.toString());
			e.printStackTrace();
			resp.setRetCode(MessageResultEnum.EXEC_FAILD.getRetCode());
			resp.setMessage(MessageResultEnum.EXEC_FAILD.getMessage());
			resp.setTotalRows(0);
		}
       return resp;
	}
	
	/**
	 * 判断操作员是否具备餐饮对应业务推送消息的角色
	 * @throws Exception 
	 */
	public boolean ifOperatorHasRole(String msgCode,List<String> userRoleIdList) throws IOException{
		boolean result = false;
		if(userRoleIdList != null && userRoleIdList.size()>0){
			 if(MSG_CODE_02541.indexOf(msgCode) >= 0){   //具备02541业务推送消息的角色有：(202,302,303,203,204,304)
				if(ifListContentElem(userRoleIdList,ROLE_202)
				 ||ifListContentElem(userRoleIdList,ROLE_302)
				 ||ifListContentElem(userRoleIdList,ROLE_303)
				 ||ifListContentElem(userRoleIdList,ROLE_203)
				 ||ifListContentElem(userRoleIdList,ROLE_204)
				 ||ifListContentElem(userRoleIdList,ROLE_304)){
					result = true;
				}
			 } else if (MSG_CODE_02542.indexOf(msgCode) >= 0) {  ////具备02542业务推送消息的角色有：(202,302,303,203)
				if(ifListContentElem(userRoleIdList,ROLE_202)
				 ||ifListContentElem(userRoleIdList,ROLE_302)
				 ||ifListContentElem(userRoleIdList,ROLE_303)
				 ||ifListContentElem(userRoleIdList,ROLE_203)){
					result = true;
				}
		     } else if (MSG_CODE_02543.indexOf(msgCode) >= 0) {  ////具备02543业务推送消息的角色有：(202,302,303,203)
				if(ifListContentElem(userRoleIdList,ROLE_202)
				 ||ifListContentElem(userRoleIdList,ROLE_302)
				 ||ifListContentElem(userRoleIdList,ROLE_303)
				 ||ifListContentElem(userRoleIdList,ROLE_203)){
					result = true;
				}
		     } else if (MSG_CODE_02544.indexOf(msgCode) >= 0) {  ////具备02544业务推送消息的角色有：(205,305)
				if(ifListContentElem(userRoleIdList,ROLE_205)
				 ||ifListContentElem(userRoleIdList,ROLE_305)){
					result = true;
				}
		     } else if (MSG_CODE_02545.indexOf(msgCode) >= 0) {  ////具备02545业务推送消息的角色有：(202,302,303,203)
		    	 if(ifListContentElem(userRoleIdList,ROLE_202)
				 ||ifListContentElem(userRoleIdList,ROLE_302)
				 ||ifListContentElem(userRoleIdList,ROLE_303)
				 ||ifListContentElem(userRoleIdList,ROLE_203)){
					result = true;
				}
		     } else if(MSG_CODE_02546.indexOf(msgCode) >= 0){   //具备02546业务推送消息的角色有：(202,302,303,203,204,304)
				if(ifListContentElem(userRoleIdList,ROLE_202)
				 ||ifListContentElem(userRoleIdList,ROLE_302)
				 ||ifListContentElem(userRoleIdList,ROLE_303)
				 ||ifListContentElem(userRoleIdList,ROLE_203)
				 ||ifListContentElem(userRoleIdList,ROLE_204)
				 ||ifListContentElem(userRoleIdList,ROLE_304)){
					result = true;
				}
			 } else if(MSG_CODE_02547.indexOf(msgCode) >= 0){   //具备02547业务推送消息的角色有：(202,302,303,203,204,304)
				if(ifListContentElem(userRoleIdList,ROLE_202)
				 ||ifListContentElem(userRoleIdList,ROLE_302)
				 ||ifListContentElem(userRoleIdList,ROLE_303)
				 ||ifListContentElem(userRoleIdList,ROLE_203)
				 ||ifListContentElem(userRoleIdList,ROLE_204)
				 ||ifListContentElem(userRoleIdList,ROLE_304)){
					result = true;
				}
			 }
		}
		return result;
	}
	
	/**
	 * 判断list中是否存在某个元素，此业务是判断某个用户角色列表中是否存在某个“合适的”角色
	 * @throws Exception 
	 */
	public boolean ifListContentElem(List<String> userRoleIdList,String role) {
		boolean result = false;
		for(String roleData : userRoleIdList){
			if(roleData.equals(role)){
				result = true;
				break;
			}
		}
		return result;
	}	
}
